﻿using FontAwesome.Sharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BOTemplatesItemsWizards
{
    public enum MoveDirection { Up = -1, Down = 1 };
    public enum ToolBarFooterAlignment { Left=0, Center, Right}

    public partial class PageElementsSetting : Form
    {
        IconChar[] m_icons = null;
        int m_addIndex = 0;
        int m_addButtonIndex = 0;
        private StringBuilder m_panelHeaderToolbar = null;
        private StringBuilder m_panelButtonsFooter = null;
        private string m_toolbarArea = string.Empty;
        private string m_footerArea = string.Empty;
        private ToolBarFooterAlignment m_toolbarAlignment = ToolBarFooterAlignment.Right;
        private ToolBarFooterAlignment m_footerAlignment = ToolBarFooterAlignment.Left;
        private string m_actionCode = string.Empty;
        private Layouts m_currentLayout = Layouts.Empty;
        private LayoutsGenerator m_lg = null;
        private string m_layoutCode = string.Empty;
        private bool m_isformlyPresent = false;
        private bool m_isGridPresent = false;
        private string m_headSettings = string.Empty;
        private string m_panelHeader = string.Empty;
        private string m_gridCRUDActionCode = string.Empty;
        private string m_gridDefinition = string.Empty;
        private string m_controlsLibraryDefinition = string.Empty;

        public string ControlsLibraryDefinition
        {
            get { return m_controlsLibraryDefinition; }
            set { m_controlsLibraryDefinition = value; }
        }

        public bool IsGridCRUD 
        {
            get { return this.chkBGridCRUD.Checked; }
            set { this.chkBGridCRUD.Checked = value; }
        }

        public string GridCRUDActionCode
        {
            get { return m_gridCRUDActionCode; }
            set { m_gridCRUDActionCode = value; }
        }

        public string GridDefinition
        {
            get { return m_gridDefinition; }
            set { m_gridDefinition = value; }
        }

        public string PanelHeader
        {
            get { return m_panelHeader; }
            set { m_panelHeader = value; }
        }

        public string HeadSettings
        {
            get { return m_headSettings; }
            set { m_headSettings = value; }
        }

        public string LayoutCode
        {
            get { return m_layoutCode; }
            set { m_layoutCode = value; }
        }

        public string ActionCode
        {
            get { return m_actionCode; }
            set { m_actionCode = value; }
        }

        public ToolBarFooterAlignment ToolbarAlignment
        {
            get { return m_toolbarAlignment; }
            set { m_toolbarAlignment = value; }
        }

        public ToolBarFooterAlignment FooterAlignment
        {
            get { return m_footerAlignment; }
            set { m_footerAlignment = value; }
        }

        public string ToolbarArea
        {
            get { return m_toolbarArea; }
            set { m_toolbarArea = value; }
        }

        public string FooterArea
        {
            get { return m_footerArea; }
            set { m_footerArea = value; }
        }

        public PageElementsSetting()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            m_icons = Enum.GetValues(typeof(IconChar)).OfType<IconChar>().OrderBy(x => x.ToString()).ToArray();

            LoadIcons(m_icons);

            base.OnLoad(e);
        }

        private void LoadIcons(IconChar[] icons)
        {
            //lvFAs.ListViewItemSorter = new IconComparer();

            imageList1.AddIcons(16, Color.Black, icons);

            lvFAs.LargeImageList = imageList1;
            lvToolbarElems.SmallImageList = imageList1;

            for (int i = 0; i < icons.Count(); i++)
            {
                lvFAs.Items.Add(icons[i].ToString(), i);
            }

            lvFAs.Sort();

            /**/
            lvFa1.LargeImageList = imageList1;
            lvButtons.SmallImageList = imageList1;
            for (int i = 0; i < icons.Count(); i++)
            {
                lvFa1.Items.Add(icons[i].ToString(), i);
            }

            lvFa1.Sort();
            /**/
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in lvFAs.SelectedItems)
            {
                ListViewItem clone = (ListViewItem)item.Clone();

                ListViewItem lvi = lvToolbarElems.Items.Insert(m_addIndex++, clone);
                lvi.SubItems.Add(this.txtToolbarAction.Text);
                lvi.ImageIndex = clone.ImageIndex;

                //lvFAs.Items.Remove(item);
                this.txtToolbarAction.Clear();
            }

            lvFAs.SelectedItems.Clear();
        }

        private static int GetInsertPosition(ListViewItem item, ListView target)
        {
            const int compareColumn = 0;
            foreach (ListViewItem targetItem in target.Items)
            {
                //if (targetItem.SubItems[compareColumn].Text.CompareTo(item.SubItems[compareColumn].Text) > 0)
                if (targetItem.SubItems[compareColumn].Text == item.SubItems[compareColumn].Text)
                {
                    return targetItem.Index;
                }
            }
            return target.Items.Count;
        }

        /* Manage Listview Up & down */
        private void MoveListItem(ListView sender, MoveDirection direction)
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }

            var currentIndex = sender.SelectedItems[0].Index;
            var item = sender.Items[currentIndex];

            if (direction == MoveDirection.Up)
            {
                if (currentIndex == 0)
                {
                    return;
                }

                if (currentIndex > 0)
                {
                    sender.Items.RemoveAt(currentIndex);
                    sender.Items.Insert(currentIndex - 1, item);
                }
            }

            if (direction == MoveDirection.Down)
            {
                if (currentIndex == sender.Items.Count - 1)
                {
                    return;
                }

                if (currentIndex < sender.Items.Count - 1)
                {
                    sender.Items.RemoveAt(currentIndex);
                    sender.Items.Insert(currentIndex + 1, item);
                }
            }

            ListView pp = new ListView();
            ListView.ListViewItemCollection p = new ListView.ListViewItemCollection(pp);
            foreach (ListViewItem m in sender.Items)
            {
                p.Add((ListViewItem)m.Clone());
            }

            sender.Items.Clear();

            foreach (ListViewItem m in p)
            {
                sender.Items.Add((ListViewItem)m.Clone());
            }

            sender.Refresh();
        }
        /* Manage Listview Up & down */

        private void button2_Click(object sender, EventArgs e)
        {
            MoveListItem(this.lvToolbarElems, MoveDirection.Up);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MoveListItem(this.lvToolbarElems, MoveDirection.Down);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.lvToolbarElems.SelectedItems.Count == 0)
            {
                return;
            }

            var item = (ListViewItem)this.lvToolbarElems.SelectedItems[0].Clone();

            var currentIndex = this.lvToolbarElems.SelectedItems[0].Index;

            this.lvToolbarElems.Items.RemoveAt(currentIndex);

            this.lvFAs.Items.Add(item);
        }

        private void btnAggiungi_Click(object sender, EventArgs e)
        {
            string m_nome = this.txtNomePulsante.Text;
            string m_action = this.txtActionPulsante.Text;

            if (lvFa1.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in lvFa1.SelectedItems)
                {
                    ListViewItem clone = (ListViewItem)item.Clone();

                    ListViewItem lvi = lvButtons.Items.Insert(m_addButtonIndex++, clone);
                    lvi.SubItems.Add(m_nome);
                    lvi.SubItems.Add(m_action);
                    lvi.ImageIndex = clone.ImageIndex;

                    //lvFa1.Items.Remove(item);
                }
            }
            else
            {
                ListViewItem lvi = lvButtons.Items.Insert(m_addButtonIndex++, new ListViewItem() { Text = "" });
                lvi.SubItems.Add(m_nome);
                lvi.SubItems.Add(m_action);
            }

            this.txtNomePulsante.Clear();
            this.txtActionPulsante.Clear();
            lvFa1.SelectedItems.Clear();
        }

        private void btnButtonPrev_Click(object sender, EventArgs e)
        {
            MoveListItem(this.lvButtons, MoveDirection.Up);
        }

        private void btnButtonSucc_Click(object sender, EventArgs e)
        {
            MoveListItem(this.lvButtons, MoveDirection.Down);
        }

        private void btnButtonDelete_Click(object sender, EventArgs e)
        {
            if (this.lvButtons.SelectedItems.Count == 0)
            {
                return;
            }

            var item = (ListViewItem)this.lvButtons.SelectedItems[0].Clone();

            var currentIndex = this.lvButtons.SelectedItems[0].Index;

            this.lvButtons.Items.RemoveAt(currentIndex);
        }

        private void chkBToolbarExists_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkBToolbarExists.Checked)
            {
                this.tabControl1.HideTabPage(this.tabPage2);
            }
            else
            {
                this.tabControl1.ShowTabPage(this.tabPage2, 1);
            }
        }

        private void chkBFooterExists_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkBFooterExists.Checked)
            {
                this.tabControl1.HideTabPage(this.tabPage3);
            }
            else
            {
                this.tabControl1.ShowTabPage(this.tabPage3, 2);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            StringBuilder m_actionCodeSb = new StringBuilder();
            m_actionCodeSb.AppendLine("/* Autogenerated toolbar and button functions... */");

            /* panel settings */
            if (this.chkBToolbarExists.Checked)
            {
                /* toolbar header settings */
                m_panelHeaderToolbar = new StringBuilder();

                m_panelHeaderToolbar.AppendFormat("<div class=\"panel-tools\" align=\"{0}\">\n", m_toolbarAlignment.ToString().ToLower());
                m_panelHeaderToolbar.AppendLine("\t\t\t\t<ul class=\"tooltip-area\">");

                if (this.chkCollapse.Checked)
                {
                    m_panelHeaderToolbar.AppendLine("\t\t\t\t\t<li><a href=\"javascript:Collapse(0)\" class=\"btn btn-collapse\" title=\"Collapse\"><i class=\"fa fa-sort-amount-asc\"></i></a></li>");
                }

                if (this.chkReload.Checked)
                {
                    m_panelHeaderToolbar.AppendLine("\t\t\t\t\t<li><a href=\"javascript:Reload(0)\" class=\"btn btn-reload\"  title=\"Reload\"><i class=\"fa fa-retweet\"></i></a></li>");
                }

                if (this.chkClose.Checked)
                {
                    m_panelHeaderToolbar.AppendLine("\t\t\t\t\t<li><a href=\"javascript:Close(0)\" class=\"btn btn-close\" title=\"Close\"><i class=\"fa fa-times\"></i></a></li>");
                }

                if (lvToolbarElems.Items.Count > 0)
                {
                    foreach (ListViewItem item in lvToolbarElems.Items)
                    {
                        if ((item.SubItems != null) && (item.SubItems.Count > 0))
                        {
                            string m_icon = NormalizeFromCamel(item.SubItems[0].Text, '-');
                            string m_action = item.SubItems[1].Text;

                            m_panelHeaderToolbar.AppendFormat("\t\t\t\t\t<li><a href=\"javascript:{0}()\" class=\"btn\" title=\"{0}\"><i class=\"fa fa{1}\"></i></a></li>\n", m_action, m_icon.ToLower());

                            if (!string.IsNullOrWhiteSpace(m_action))
                            {
                                m_actionCodeSb.AppendFormat("function {0}()\n{{\n}}\n\n", m_action);
                            }
                        }
                    }
                }
                m_panelHeaderToolbar.AppendLine("\t\t\t\t</ul>");
                m_panelHeaderToolbar.AppendLine("\t\t\t</div>");
            }
            /* toolbar header settings */

            /* footer settings */
            if (this.chkBFooterExists.Checked)
            {
                m_panelButtonsFooter = new StringBuilder();

                m_panelButtonsFooter.AppendFormat("<footer class=\"panel-footer\" align=\"{0}\">\n", m_toolbarAlignment.ToString().ToLower());

                m_panelButtonsFooter.AppendLine("\t\t\t\t<button type=\"invia\" class=\"btn\" data-color=\"#F4AD41\">Invia</button>");
                m_panelButtonsFooter.AppendLine("\t\t\t\t<button type=\"reset\" class=\"btn\">Cancel</button>");

                if (lvButtons.Items.Count > 0)
                {
                    foreach (ListViewItem item in lvButtons.Items)
                    {
                        if ((item.SubItems != null) && (item.SubItems.Count > 0))
                        {
                            string m_icon = NormalizeFromCamel(item.SubItems[0].Text, '-');
                            string m_action = item.SubItems[1].Text;

                            string m_iconTag = (!string.IsNullOrWhiteSpace(m_icon) ? "<i class=\"fa fa" + m_icon.ToLower() + "\"></i>" : string.Empty);

                            m_panelButtonsFooter.AppendFormat("\t\t\t\t<button type=\"button\" class=\"btn\" onclick=\"javascript:{0}()\">{1}{0}</button>\n", m_action, m_iconTag);

                            if (!string.IsNullOrWhiteSpace(m_action))
                            {
                                m_actionCodeSb.AppendFormat("function {0}()\n{{\n}}\n\n", m_action);
                            }
                        }
                    }
                }
                m_panelButtonsFooter.AppendLine("\t\t\t</footer>");
            }
            /* footer settings */

            /* prepare public properties... */
            m_toolbarArea = m_panelHeaderToolbar.ToString();
            m_footerArea = m_panelButtonsFooter.ToString();

            m_actionCode = m_actionCodeSb.ToString();

            m_lg = new LayoutsGenerator();
            m_lg.IsGridCRUD = this.chkBGridCRUD.Checked;
            //m_lg.PanelHeader = this.txtHeader1.Text;
            m_layoutCode = m_lg.Create(m_currentLayout);

            m_headSettings = CreateHeadSettings();

            m_panelHeader = this.txtHeader1.Text;

            m_gridCRUDActionCode = m_lg.GridCRUDActionCode;

            m_gridDefinition = m_lg.GridDefinition;

            m_controlsLibraryDefinition = m_lg.ControlLibraryDefinition;
        }

        private void rbToolbarAlignment_CheckedChanged(object sender, EventArgs e)
        {
            m_toolbarAlignment = (ToolBarFooterAlignment)Enum.Parse(typeof(ToolBarFooterAlignment), ((RadioButton)sender).Text);
        }

        private void rbFooterAlignment_CheckedChanged(object sender, EventArgs e)
        {
            m_footerAlignment = (ToolBarFooterAlignment)Enum.Parse(typeof(ToolBarFooterAlignment), ((RadioButton)sender).Text);
        }

        private string NormalizeFromCamel(string value, char separator)
        {
            if (value.Length > 0)
            {
                var result = new List<char>();
                char[] array = value.ToCharArray();
                foreach (var item in array)
                {
                    if (char.IsUpper(item))
                    {
                        result.Add(separator);
                    }
                    result.Add(item);
                }

                return new string(result.ToArray());
            }
            return value;
        }

        private void PanelChanged(object sender, EventArgs e)
        {
            string m_choosed = ((RadioButton)sender).Name;

            if (m_choosed == "rbPanelEmpty")
            {
                this.chkBGridCRUD.Enabled = false;
                m_currentLayout = Layouts.Empty; 
            }

            if (m_choosed == "rbPanelTwo")
            {
                this.chkBGridCRUD.Enabled = false;
                m_currentLayout = Layouts.TwoPanels;
            }

            if (m_choosed == "rbPanelFour")
            {
                this.chkBGridCRUD.Enabled = false;
                m_currentLayout = Layouts.FourPanels;
            }

            if (m_choosed == "rbPanelFormly")
            {
                this.chkBGridCRUD.Enabled = false;
                m_currentLayout = Layouts.Formly;
            }

            if (m_choosed == "rbPanelFormlyTwo")
            {
                m_isformlyPresent = true;
                m_isGridPresent = false;

                this.chkBGridCRUD.Enabled = false;
                m_currentLayout = Layouts.FormlyTwoPanels;
            }

            if (m_choosed == "rbPanelFormlyFour")
            {
                m_isformlyPresent = true;
                m_isGridPresent = false;

                this.chkBGridCRUD.Enabled = false;
                m_currentLayout = Layouts.FormlyFourPanels;
            }

            if (m_choosed == "rbPanelFormlyGrid")
            {
                m_isformlyPresent = true;
                m_isGridPresent = true;

                this.chkBGridCRUD.Enabled = true;
                m_currentLayout = Layouts.FormlyGrid;
            }

            if (m_choosed == "rbPanelGrid")
            {
                m_isformlyPresent = false;
                m_isGridPresent = true;

                this.chkBGridCRUD.Enabled = true;
                m_currentLayout = Layouts.Grid;
            }
        }

        private void chkBGridCRUD_CheckedChanged(object sender, EventArgs e)
        {
            if (m_lg != null)
            {
                m_lg.IsGridCRUD = this.chkBGridCRUD.Checked;
            }
        }

        private string CreateHeadSettings()
        {
            string retValue = string.Empty;

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<asp:PlaceHolder ID=\"PlaceHolder1\" runat=\"server\">");

            if (m_isformlyPresent)
            {
                sb.AppendLine("<%: Styles.Render(\"~/bundles/Formly/css\") %>");
                sb.AppendLine("<%: Scripts.Render(\"~/bundles/Formly\") %>");
            }

            if (m_isGridPresent)
            {
                sb.AppendLine("<%: Styles.Render(\"~/bundles/Datatables/css\") %>");
                sb.AppendLine("<%: Scripts.Render(\"~/bundles/Datatables\") %>");
            }
            sb.AppendLine("</asp:PlaceHolder>");

            sb.AppendLine("<!-- Common -->");
            sb.AppendLine("<script type=\"text/javascript\" lang=\"javascript\" src=\"../Scripts/Formly/FormlyHelper.js\"></script>");
            sb.AppendLine("<script type=\"text/javascript\" lang=\"javascript\" src=\"../Scripts/GrayParrot.Core.js\"></script>");
            sb.AppendLine("<script type=\"text/javascript\" lang=\"javascript\" src=\"../Scripts/GrayParrot.AngularJS.Directives.DateTimePicker.js\"></script>");
            sb.AppendLine("<script type=\"text/javascript\" lang=\"javascript\" src=\"../Scripts/GrayParrot.AngularJS.Directives.FileUpload.js\"></script>");
            sb.AppendLine("<script type=\"text/javascript\" lang=\"javascript\" src=\"../Scripts/GrayParrot.AngularJS.js\"></script>");
            sb.AppendLine("<script type=\"text/javascript\" lang=\"javascript\" src=\"../Scripts/GrayParrot.DataTables.js\"></script>");
            sb.AppendLine("<!-- Common -->");

            retValue = sb.ToString();

            return retValue;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            // if cancel then empty page is default...
            m_lg = new LayoutsGenerator();
            //m_lg.PanelHeader = this.txtHeader1.Text;
            m_layoutCode = m_lg.Create(Layouts.Empty);
        }
    }
}
